<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="SIM卡号" prop="msisdn">
        <el-input v-model="queryParams.msisdn" placeholder="请输入SIM卡号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="关联设备" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入关联设备" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="ICCID号" prop="iccid">
        <el-input v-model="queryParams.iccid" placeholder="请输入ICCID号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="运营商" prop="states">
        <el-select v-model="queryParams.operator" placeholder="请选择">
          <el-option label="联通" value="unicom" />
          <el-option label="移动" value="mobile" />
          <el-option label="电信" value="telecom" />
        </el-select>
      </el-form-item>
      <el-form-item label="绑定状态" prop="bindStatus">
        <el-select v-model="queryParams.bindStatus" placeholder="请选择">
          <el-option label="已绑定" value="1" />
          <el-option label="未绑定" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['basic:sim:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleImport"
          v-hasPermi="['basic:sim:import']">导入</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- <BasicTable
      :column="column"
      :handel="handel"
      :tableData="simList"
      :isSelect="true"
      @select="ChangeSelect"
    >
    </BasicTable> -->
    <el-table border stripe v-loading="loading" :data="simList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="30" align="center" fixed="left" />
      <el-table-column label="关联设备" align="left" prop="code" />
      <el-table-column label="MSISDN/SIM卡号" align="left" prop="msisdn" />
      <el-table-column label="ICCID号" align="left" prop="iccid" />
      <el-table-column label="IMSI号" align="left" prop="imsi" />
      <el-table-column label="运营商" width="100" align="center" prop="operator">
        <template #default="scope">
          <dict-tag :options="basic_sim_operator" :value="scope.row.operator" />
        </template>
      </el-table-column>
      <el-table-column label="SIM卡状态" width="100" align="center" prop="states">
        <template #default="scope">
          <dict-tag :options="basic_sim_operator" :value="scope.row.states" />
        </template>
      </el-table-column>
      <el-table-column label="在线状态" width="80" align="center" prop="onlines" />
      <el-table-column label="数据用量(MB)" align="center" prop="dataUsage" />
      <el-table-column label="最后会话时间" width="160" align="center" prop="sessionTime" />
      <el-table-column label="操作" width="180" align="center" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button link type="success" icon="Edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['basic:sim:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"
              v-hasPermi="['basic:sim:remove']"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
    <!-- 添加或修改SIM卡号对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="simRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="SIM卡号" prop="msisdn">
          <el-input v-model="form.msisdn" placeholder="请输入SIM卡号" :disabled="!isAdd" />
        </el-form-item>
        <el-form-item label="ICCID号" prop="iccid">
          <el-input v-model="form.iccid" placeholder="请输入ICCID号" />
        </el-form-item>
        <el-form-item label="IMSI" prop="imsi">
          <el-input v-model="form.imsi" placeholder="请输入IMSI" />
        </el-form-item>
        <el-form-item label="运营商" prop="operator">
          <el-select v-model="form.operator" placeholder="请选择">
            <el-option label="联通" value="unicom" />
            <el-option label="移动" value="mobile" />
            <el-option label="电信" value="telecom" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" action="#" :http-request="httpRequest"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag :data="upload.form">
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <el-form :model="upload.form" ref="uploadForm" label-width="100px">
              <div class="el-upload__tip">
                <el-checkbox v-model="upload.form.updateSupport" label="是否更新已经存在的数据" />
              </div>
            </el-form>
            <br />
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
              @click="handleTemplateImport">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Sim">
import { getToken } from "@/utils/auth"
import BasicTable from '@/components/BasicTable/BasicTable.vue'
import { listSim, getSim, delSim, addSim, updateSim } from "@/api/basic/sim";
import { ref } from 'vue';
const { proxy } = getCurrentInstance();
const { basic_sim_operator } = proxy.useDict('basic_sim_operator');
const simList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
/** 导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  form: {
    // 是否更新已经存在的用户数据
    updateSupport: 0,
    areaId: undefined,
  },
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: "basic/sim/import/data"
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    msisdn: undefined,
    iccid: undefined,
    code: undefined,
    operator: undefined,
    bindStatus: undefined,
  },
  rules: {
    msisdn: [
      { required: true, message: "MSISDN/SIM卡号不能为空", trigger: "blur" }
    ],
    iccid: [
      { required: true, message: "ICCID号不能为空", trigger: "blur" }
    ],
    imsi: [
      { required: true, message: "IMSI不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询SIM卡号列表 */
function getList() {
  loading.value = true;
  listSim(queryParams.value).then(response => {
    simList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    msisdn: null,
    iccid: null,
    imsi: null,
    operator: null,
    states: null,
    onlines: null,
    dataUsage: null,
    sessionTime: null,
    smsUsage: null,
    voiceUsage: null,
    syncState: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("simRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.msisdn);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

const isAdd = ref(false)
/** 新增按钮操作 */
function handleAdd() {
  reset();
  isAdd.value = true
  open.value = true;
  title.value = "添加SIM卡号";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  isAdd.value = false
  reset();
  const _msisdn = row.msisdn || ids.value
  getSim(_msisdn).then(response => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改SIM卡号";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["simRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (!isAdd.value) {
        updateSim(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addSim(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _msisdns = row.msisdn || ids.value;
  proxy.$modal.confirm('是否确认删除SIM卡号编号为"' + _msisdns + '"的数据项？').then(function () {
    loading.value = true;
    return delSim(_msisdns);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}
/** 导入按钮操作 */
function handleImport() {
  upload.title = 'SIM卡导入';
  upload.open = true;
}

/** 获取导入模板按钮操作 */
function handleTemplateImport() {
  proxy.download('/basic/sim/import/template', {}, `SIM卡号导入模板.xlsx`)
}
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadForm"].validate((valid) => {
    if (valid) {
      proxy.$refs["uploadRef"].submit();
      upload.open = false
      getList()
    } else {
      upload.open = false
      console.log('error submit!!');
      return false;
    }
  });
};
/** 文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};
function httpRequest(data) {
  // 封装FormData对象
  data.data[data.filename] = data.file
  upload.open = false;
  upload.isUploading = false;
  proxy.importFile(upload.url, data.data).then(res => {
    proxy.$refs["uploadRef"].handleRemove(data.file);
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + res.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    getList();
  }).catch(err => {
    proxy.$refs["uploadRef"].handleRemove(data.file);
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + err + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    getList();
  })
}
getList();
</script>

<style scoped>
.el-form--inline .el-form-item {
  margin-right: 20px;
}
</style>